home *** CD-ROM | disk | FTP | other *** search
/ MacTech 1 to 12 / MacTech-vol-1-12.toast / Source / MacTech® Magazine / Volume 07 - 1991 / 07.12 Dec 91 / MacSocket Code / client.c next >
Encoding:
C/C++ Source or Header  |  1991-04-11  |  1.7 KB  |  81 lines  |  [TEXT/KAHL]

  1. /***
  2.  ***
  3.  *** To send data between stream sockets (having communication style
  4.  *** SOCK_STREAM)
  5.  *** Code based on an example taken from SUN® Network Programming Guide,
  6.  *** chapter 10, A Socket-Based Interprocess Communications Tutorial,
  7.  *** Revision A, of 27 March 1990, Fig. 10-9, pp. 266-267.
  8.  ***
  9.  ***/
  10.  
  11. #ifdef    SUN_C
  12. #include    <sys/types.h>
  13. #include    <sys/socket.h>
  14. #include    <netinet/in.h>
  15. #include    <netdb.h>
  16. #include    <stdio.h>
  17. #else    SUN_C
  18. /*
  19. #define    MAC_APPL
  20. */
  21. #include    <console.h>
  22. #include    "MacSocket.h"
  23. #define    bcopy(s1, s2, n)    memcpy((s2), (s1), (n))
  24. #endif    SUN_C
  25.  
  26. #define    Port    (31768)
  27. #define    DATA    "\nFrom: client\nTo:   server\nMssg: Hello server!\n"
  28.  
  29. main()
  30. {
  31.     int        sock, mssgSize;
  32.     struct    sockaddr_in server;
  33.     union
  34.     {
  35.         long            address;
  36.         unsigned char    domain[4];
  37.     } host;
  38.     char    buf[1024];
  39.     
  40. #ifdef    MAC_APPL
  41.     /* prevent showing informative MacTCP/IP messages */
  42.     SetDialogShowTime(0);
  43. #endif    MAC_APPL
  44.     
  45.     /* Create socket. */
  46.     sock = socket(AF_INET, SOCK_STREAM, 0);
  47.     if (sock < 0)
  48.     {
  49.         perror("opening stream socket");
  50.         exit(1);
  51.     }
  52.     /* Connect socket using address 192.6.1.30 and port# */
  53.     server.sin_family = AF_INET;
  54.     host.domain[0] = 192;
  55.     host.domain[1] = 6;
  56.     host.domain[2] = 1;
  57.     host.domain[3] = 30;
  58.     bcopy((char*)&host.address, (char*)&server.sin_addr, 4);
  59.     server.sin_port = Port;
  60.  
  61.     if (connect(sock, (struct sockaddr_in *)&server, sizeof server) < 0)
  62.     {
  63.         perror("connecting stream socket");
  64.         exit(1);
  65.     }
  66.     if (send(sock, DATA, sizeof DATA, 0) < 0)
  67.     {
  68.         perror("writing on stream socket");
  69.         exit(1);
  70.     }
  71.     if ((mssgSize = recv(sock, buf, sizeof buf, 0)) < 0)
  72.     {
  73.         perror("reading on stream socket");
  74.         exit(1);
  75.     }
  76.     buf[mssgSize] = '\0';
  77.     printf("Client--> %s\n", buf);
  78.     close(sock);
  79.     exit(0);
  80. }
  81.